export function usePostMessage({
  voiceFunc,
  textFunc,
  tokenFunc,
  deviceIdFunc,
}: {
  voiceFunc: (status: boolean) => void;
  textFunc: (text: string) => void;
  tokenFunc: (token: string) => void;
  deviceIdFunc?: (deviceId: string, label: string) => void;
}) {
  const isIframe = window.self !== window.top
  const postMessage = (type: string, data: unknown) => {
    if (!isIframe) return
    // 发送消息到父页面
    window.parent.postMessage({ type, data }, '*')
  }

  const onMessage = () => {
    // 监听父页面发送的消息 可自定义任何类型的消息
    window.addEventListener('message', (event) => {
      switch (event.data.type) {
        case 'TEXT_DATA':
          textFunc(event.data.data)
          // voiceFunc(true)
          break
        case 'RECORD_STATUS':
          console.log('event.data.status', event.data.status)
          voiceFunc(event.data.status !== 'start')
          break
        case 'SEND_TOKEN':
          tokenFunc(event.data.data)
          break
        case 'SEND_DEVICE_ID':
          if (deviceIdFunc) {
            deviceIdFunc(event.data.data, event.data.label)
          }
          break
      }
    })
  }

  onMessage()
  return { postMessage, isIframe, onMessage }
}

